/**
 * 测试Native Messaging Host的客户端
 */
const { spawn } = require('child_process');

class TestClient {
    constructor(hostPath) {
        this.hostProcess = spawn(hostPath, [], {
            stdio: ['pipe', 'pipe', 'inherit']
        });

        this.setupMessageHandling();
    }

    setupMessageHandling() {
        this.hostProcess.stdout.on('data', (data) => {
            this.handleOutput(data);
        });

        this.hostProcess.stdin.on('error', (error) => {
            console.error('STDIN error:', error);
        });

        this.hostProcess.on('close', (code) => {
            console.log(`Host process exited with code ${code}`);
        });
    }

    handleOutput(data) {
        // 简单的输出处理，实际协议更复杂
        console.log('Host output:', data.toString());
    }

    sendMessage(message) {
        const messageStr = JSON.stringify(message);
        const lengthBuffer = Buffer.alloc(4);
        lengthBuffer.writeUInt32LE(Buffer.byteLength(messageStr), 0);

        this.hostProcess.stdin.write(lengthBuffer);
        this.hostProcess.stdin.write(messageStr);
    }

    testCommunication() {
        // 测试ping
        this.sendMessage({
            action: 'ping',
            requestId: 'test-1'
        });

        // 测试RPA命令
        setTimeout(() => {
            this.sendMessage({
                action: 'rpaCommand',
                requestId: 'test-2',
                command: 'openBrowser',
                args: { url: 'https://example.com' }
            });
        }, 1000);
    }
}

if (require.main === module) {
    const client = new TestClient('chrome_native_messaging_host.exe');
    client.testCommunication();
}